<?php

namespace app\common\behavior;


use app\common\library\agent\comission\impl\CommonCommissionListener;
use app\common\model\GoodsSpec;
use app\common\model\User;
use think\Exception;
use think\Log;

class Order
{
    public function afterPay(&$order)
    {

        $this->setUpper($order);

        Log::record("开始计算分润");
        $orderGoods = $order->goods;
        foreach ($orderGoods as $orderGood) {
            Log::record("商品 --> " . json_encode($orderGood));
            $specId = $orderGood->goods_spec_id;
            $spec = GoodsSpec::get($specId);
            $commissonType = $spec->commission_type;
            $commissons = htmlspecialchars_decode($spec->commissions);
            Log::record("分润设置 --> " . $commissons);
            $commissonSetting = json_decode($commissons, true);
            $clazz = '\\app\\common\\library\\agent\\comission\\impl\\' . ucfirst($commissonType) . 'Commission';
            Log::record("分润方法 --> " . $clazz);
            if (!class_exists($clazz)) {
                Log::record("$clazz 分佣方式不存在");
                return;
            }
            $commisson = new $clazz;
            $commisson->config($commissonSetting);
            $commisson->setListener(new CommonCommissionListener());
            $commisson->doCommission($commissonType, $order, $orderGood);
        }
    }

    private function setUpper($order)
    {
        $user = User::get($order->user_id);
        if ($user->agent_level == 4 && $order->share_id) {
            $shareUser = User::get($order->share_id);

            Log::record("下单者是普通用户");
            if (!$user->upper_id && $shareUser) {
                if ($shareUser->agent_level < 4) {
                    Log::record("分享者是代理");
                    $upper = $shareUser;
                } else {
                    Log::record("分享者是普通用户");
                    if ($shareUser->upper_id) {
                        $upper = User::get($shareUser->upper_id);
                    }
                }
                if(isset($upper)){
                    Log::record("没有上级");
                    Log::record("确认上级为" . $order->share_id);
                    $user->upper_id = $order->share_id;
                    $user->ranking = $upper->ranking . $user->ranking;
                    $user->save();
                }
            }
        }
    }
}
